package foodmaterial.action;

import foodmaterial.entity.SysUser;
import foodmaterial.service.InitService;
import foodmaterial.utils.Constants;
import foodmaterial.utils.FileTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin(allowCredentials = "true")
@RequestMapping("/readImage")
public class ReadImage {

    @Autowired
    private InitService initService ;

    @GetMapping("/showCredentials")
    public ModelAndView print(@RequestParam("image") String image) {
        Map<String,Object> map = new HashMap<>();
        map.put("type","credentials");
        map.put("image",image);
        map.put("backAddress",initService.querySysParamsByCode(Constants.IMAGE_SERVER_ADDRESS).getParamValue()) ;
        return new ModelAndView("showCredentials","params",map);
    }

    @RequestMapping(value = "/{type}/{image}",method = RequestMethod.GET)
    public void read(@PathVariable("type") String type,
                     @PathVariable("image") String image,
                     HttpServletResponse response) {
        StringBuilder imageSavePath = new StringBuilder();
        SysUser userDetails = (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if ("credentials".equals(type))
            imageSavePath.append(initService.querySysParamsByCode(Constants.CREDENTIALS_PATH).getParamValue()) ;
        else
            imageSavePath.append(initService.querySysParamsByCode(Constants.FOOD_PATH).getParamValue()) ;
        imageSavePath.append(type).append('/').append(userDetails.getDb()).append('/').append(image) ;
        readImage(imageSavePath.toString(),response);
    }

    public static void readImage(String imageSavePath,HttpServletResponse response) {
        DataInputStream dis=null;
        FileInputStream fis=null;
        OutputStream out = null ;
        try {
            fis=new FileInputStream(imageSavePath);
            dis=new DataInputStream(fis);
            out = response.getOutputStream() ;
            byte[] temp = new byte[8192];
            int len = 0 ;
            while((len = dis.read(temp)) > 0){
                out.write(temp,0,len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException(e) ;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e) ;
        }finally{
            FileTools.close(dis) ;
            FileTools.close(fis) ;
            FileTools.close(out) ;
        }
    }
}
